import { ComponentDefinition } from "@/types/component";

/**
 * 全局组件数据存储
 */
export class ComponentDataStore {
    private static instance: ComponentDataStore;
    private components: Map<string, ComponentDefinition> = new Map();
    private loadedLibraries: Set<string> = new Set();

    private constructor() {}

    public static getInstance(): ComponentDataStore {
        if (!ComponentDataStore.instance) {
            ComponentDataStore.instance = new ComponentDataStore();
        }
        return ComponentDataStore.instance;
    }

    // 添加组件到存储
    addComponent(component: ComponentDefinition, library: string): void {
        const fullKey = `${library}.${component.name}`;
        this.components.set(fullKey, component);
        this.loadedLibraries.add(library);
    }

    // 根据名称获取组件定义
    getComponent(componentName: string, library?: string): ComponentDefinition | undefined {
        if (library) {
            // 精确查找指定库的组件
            return this.components.get(`${library}.${componentName}`);
        } else {
            // 模糊查找所有库
            for (const [key, component] of this.components) {
                if (key.endsWith(`.${componentName}`) || 
                    (component.aliases && component.aliases.includes(componentName))) {
                    return component;
                }
            }
            return undefined;
        }
    }

    // 获取所有组件
    getAllComponents(): ComponentDefinition[] {
        return Array.from(this.components.values());
    }

    // 获取指定库的所有组件
    getComponentsByLibrary(library: string): ComponentDefinition[] {
        const result: ComponentDefinition[] = [];
        for (const [key, component] of this.components) {
            if (key.startsWith(`${library}.`)) {
                result.push(component);
            }
        }
        return result;
    }

    // 检查库是否已加载
    isLibraryLoaded(library: string): boolean {
        return this.loadedLibraries.has(library);
    }

    // 清空所有组件数据
    clear(): void {
        this.components.clear();
        this.loadedLibraries.clear();
    }

    // 获取已加载的库列表
    getLoadedLibraries(): string[] {
        return Array.from(this.loadedLibraries);
    }
}